/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package blms.repository.inmemory;

import java.util.Collection;
import java.util.List;

import blms.domain.League;
import blms.domain.Match;
import blms.repository.MatchRepository;

/**
 * Simple in-memory repository of matches. This implementation may be used to
 * load and store matches either in memory.
 * 
 * @author João Arthur
 * @author Jonhnny Weslley
 * @author Thiago Emmanuel
 * @version 1.00, 21/04/2008
 * @since 1.0
 */
public class InMemoryMatchRepository extends
		InMemoryRepositoryWithAutoIncrementId<Match> implements MatchRepository {

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.repository.inmemory.InMemoryRepositoryWithAutoIncrementId#add(blms.domain.Identifiable)
	 */
	@Override
	public void add(final Match match) {
		super.add(match);
		final League league = match.getLeague();
		league.getMatches().add(match);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.repository.inmemory.InMemoryRepository#update(blms.domain.Identifiable)
	 */
	@Override
	public void update(final Match match) {
		final Match oldMatch = entities.put(match.getId(), match);
		if (oldMatch != null) {
			final League league = oldMatch.getLeague();
			final List<Match> matchesList = league.getMatches();
			matchesList.remove(oldMatch);
			matchesList.add(match);
			match.setLeague(league);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.repository.inmemory.InMemoryRepository#remove(blms.domain.Identifiable)
	 */
	@Override
	public void remove(final Match match) {
		super.remove(match);
		final League league = match.getLeague();
		league.getMatches().remove(match);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.repository.inmemory.InMemoryRepository#removeAll()
	 */
	@Override
	public void removeAll() {
		final Collection<Match> matches = getAll();
		for (final Match match : matches) {
			match.getLeague().getMatches().remove(match);
		}
		super.removeAll();
	}

}
